<template>
  <div class="yy-nurse-sign">
    <div class="yy-nurse-sign_doctor">
      <div class="yy-nurse-sign_doctor-item">
        <div class="yy-nurse-sign_header">
          <div class="yy-nurse-sign_header-title">出诊科目</div>
          <div class="yy-nurse-sign_header-search">
             <DepartSelector placeholder="请选择科室" @change="onChangeDepart" @blur="onSetCardNumInputFocus"/>
          </div>
        </div>
        <div class="yy-nurse-sign_body yy-flex-table_container">
          <WidgetTable
              :is-loading="itemTable.isLoading"
              :columns="itemTable.columns"
              :data="itemTable.data"
              :options="itemTable.options"
              :selectedRow="selectedItem"
              @current-change="onSelectItem"
          />
        </div>
      </div>
      <div class="yy-nurse-sign_doctor-list">
        <div class="yy-nurse-sign_header">
          <div class="yy-nurse-sign_header-title">出诊医生</div>
          <div class="yy-nurse-sign_header-search">
            <el-input
                v-model="searchDoctorKey"
                placeholder="输入关键字搜索"
                prefix-icon="Search"
                @input.stop="onFilterDoctor"
                clearable
                @click.stop
                @blur.stop="onSetCardNumInputFocus"
            />
          </div>
        </div>
        <div class="yy-nurse-sign_body yy-flex-table_container">
          <WidgetTable
              :is-loading="doctorTable.isLoading"
              :columns="doctorTable.columns"
              :data="doctorTable.data"
              :formats="doctorTable.formats"
              :options="doctorTable.options"
              :selected-row="selectedDoctor"
              @current-change="onSelectDoctor"
          />
        </div>
      </div>
    </div>
    <div class="yy-nurse-sign_patient">
      <div class="yy-nurse-sign_header yy-nurse-sign_patient-header">
        <div>
          <el-button @click="listTodayEmployeePatient()"><el-icon><Refresh /></el-icon></el-button>
        </div>
        <div class="yy-nurse-sign_header-search" style="margin: 0 10px; max-width: 120px;">
          <el-select v-model="patientCard.state" placeholder="请选择状态" @change="listTodayEmployeePatient()" @blur="onSetCardNumInputFocus">
            <el-option :key="-1" :value="-1" label="全部"></el-option>
            <el-option v-for="item in QueueItemModel.queueStatusArr" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </div>
        <div class="yy-nurse-sign_header-search" style="margin: 0 10px; max-width: 120px;">
          <el-select v-model="patientCard.source" placeholder="请选择来源" @change="listTodayEmployeePatient()" @blur="onSetCardNumInputFocus">
            <el-option :key="'-1'" :value="'-1'" label="全部"></el-option>
            <el-option v-for="item in QueueItemModel.queueSourceArr" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </div>
        <div style="margin-left: auto;display: flex; align-items: center;">
          <div>
            <el-input
                placeholder="输入关键字搜索"
                ref="patientCardNumInputRef"
                autofocus
                v-model="patientCard.value"
                style="min-width: 240px;"
                @change="onSetCardNumInputFocus"
                clearable
            >
              <template #prepend>
                <el-select v-model="patientCard.type"  @change="onSelectPatientCardType" style="width: 80px"  @blur="onSetCardNumInputFocus">
                  <el-option label="读卡" value="card" />
                  <el-option label="搜索" value="name" />
                </el-select>
              </template>
            </el-input>
          </div>
          <el-button color="#009688" style="margin-left: 10px;" @click="onSearchPatient">查询</el-button>
        </div>
      </div>
      <div class="yy-nurse-sign_body">
        <WidgetTable
            :is-loading="patientTable.isLoading"
            :columns="patientTable.columns"
            :data="patientTable.data"
            :paging-data="patientTable.paging"
            :formats="patientTable.formats"
            :context-menu="patientTable.contextMenu"
        />
      </div>
    </div>
  </div>
  <SetPatientToEmployeeDialog ref="setPatientToEmployeeDialogRef" @changeSignSuccess="onSetDoctorSuccess"/>
  <SetPatientToPriorityDialog ref="setPatientToPriorityDialogRef"/>
  <PatientSignSuccessDialog ref="patientSignSuccessDialogRef"/>
  <PatientSearchDialog ref="patientSearchDialogRef" @rebackCardNo="onSetReadCardNo" @cancelSearchCardNoDialog="onSetCardNumInputFocus"/>
</template>

<script lang="ts" setup>
import WidgetTable from "@/components/widget/WidgetTable.vue";
import {onBeforeMount, onBeforeUnmount, reactive, ref} from "vue";
import {TableColumn} from "@/model/Definition";
import {QueueScheduleModel} from "@/model/QueueScheduleModel";
import NurseClientApi from "@/api/nurse";
import {Refresh} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {QueueRegItemModel} from "@/model/QueueRegItemModel";
import {EmployeeModel} from "@/model/EmployeeModel";
import {formatDate} from "@/utils/yayi";
import {QueueItemModel, QueueStateEnum} from "@/model/QueueItemModel";
import PatientSignSuccessDialog from "@/views/nurse/PatientSignSuccessDialog.vue";
import DepartSelector from "@/components/Business/DepartSelector.vue";
import SetPatientToEmployeeDialog from "./SetPatientToEmployeeDialog.vue";
import PatientSearchDialog from "@/views/nurse/PatientSearchDialog.vue";
import StorageUtils from '@/utils/StorageUtils'
import SetPatientToPriorityDialog from "@/views/nurse/SetPatientToPriorityDialog.vue";


const itemTable = reactive<{
  isLoading: boolean,
  paging?: any,
  columns: TableColumn[],
  data: QueueScheduleModel[],
  options?: any,
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"itemName",
      "label":"科目",
      "showable":true
    },{
      "field":"departName",
      "label":"科室",
      "showable":true
    },
  ],
  options: {
    highlight: true,
    isSingleSelect: true
  },
  data: []
})

const doctorTable = reactive<{
  isLoading: boolean,
  paging?: any,
  columns: TableColumn[],
  data: QueueScheduleModel[],
  options?: any,
  formats?: any
}>({
  isLoading: false,
  columns: [
  {
      "field":"doctorName",
      "label":"医生",
      "showable":true
    },{
      "field":"roomName",
      "label":"诊室",
      "showable":true
    },{
      "field":"awaitCount",
      "label":"候诊",
      "showable":true,
      width: 60
    },
  ],
  options: {
    highlight: false,
    isSingleSelect: false
  },
  formats: {
    'doctorName': {
      labelFormat: (val, row) => val + `(${row.doctorCode})`
    },
    'action': {
      items: [
      ]
    }
  },
  data: []
})

const patientTable = reactive<{
  isLoading: boolean,
  paging?: any,
  columns: TableColumn[],
  data: QueueItemModel[],
  options?: any,
  formats?: any,
  contextMenu?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"patientName",
      "label":"患者",
      "showable":true,
      "fixed": "left",
    },
    {
      "field":"registerNo",
      "label":"号序",
      "showable":true,
      "fixed": "left",
      "width": 60
    },
    // {
    //   "field":"priority",
    //   "label":"类型",
    //   "showable":true
    // },
    {
      "field":"doctorName",
      "label":"医生",
      "showable":true
    },
    {
      "field":"departName",
      "label":"科室",
      "showable":true,
    },
    {
      "field":"patientCardNo",
      "label":"卡号",
      "showable":true,
    },
    {
      "field":"patientIdCardNo",
      "label":"证件号",
      "showable":true,
      "width": 170
    },
    {
      "field":"scheduleFlag",
      "label":"预约时段",
      "showable":true,
      "width": 110
    },
    {
      "field":"registerTime",
      "label":"挂号时间",
      "showable":true,
      "width": 160
    },
    {
      "field":"signTime",
      "label":"签到时间",
      "showable":true,
      "width": 160
    },{
      "field":"state",
      "label":"状态",
      "showable":true,
      "align": "center",
      'fixed': "right",
      "width": 90
    },
    // {
    //   "field":"action",
    //   "label":"操作",
    //   "showable":true,
    //   "fixed": "right",
    //   "width": 130
    // },
  ],
  data: [],
  paging: {
    isPaging: true,
    total: 0,
    pageIndex: 1,
    pageSize: 30,
    pageChange: (pageIndex) => {
      if (_timeout) {
        clearTimeout(_timeout)
        _timeout = null
      }
      listTodayEmployeePatient(pageIndex)
    }
  },
  options: {
    highlight: true
  },
  formats: {
    'scheduleFlag': {
      textType:'text',
      labelFormat: (val, row) => {
        return val ? (row.scheduleFromTime || '') + ' - ' + (row.scheduleToTime || '') : ''
      }
    },
    'scheduleDate': {
      labelFormat: (val) => formatDate(val, 'YYYY-MM-DD')
    },
    'registerTime': {
      labelFormat: (val) => formatDate(val)
    },
    'signTime': {
      labelFormat: (val) => formatDate(val)
    },
    'doctorName': {
      labelFormat: (val, row) => {
        if(val) {
          return  val + `(${row.doctorCode})`
        }
        return ''
      }
    },
    'state': {
      textType: 'tag',
      typeFormat: (val, row) =>  {
        return QueueItemModel.getQueueState(val)?.type
      },
      labelFormat: (val, row) => {
        return QueueItemModel.getQueueState(val)?.label
      }
    },
    'action': {
      items: [
        // {
        //   elType: 'button',
        //   label: '指派',
        //   type: 'info',
        //   value: 'setDoctor',
        //   atClick: (row) => onSetPatientEmployee(row)
        // },
        // {
        //   elType: 'button',
        //   label: '签到', value: 'sign',
        //   atClick: (row) => onSignPatientByCardNo(row),
        //   condition: (row) => [QueueStateEnum.AWAIT_SIGN, QueueStateEnum.AWAIT_REVIEW, QueueStateEnum.ALREADY_PASSED, QueueStateEnum.ALREADY_COMPLETED].includes(row.state)
        // },
        // {
        //   elType: 'button',
        //   label: '取号', value: 'number',
        //   atClick: (row) => onNumberPatientByCardNo(row),
        //   condition: (row) => [QueueStateEnum.AWAIT_CALL, ].includes(row.state)
        // },
      ]
    }
  },
  contextMenu: {
    title: (row, column) => {
      return row['patientName'] + `(${row['registerNo'] ? row['registerNo'] : '未签到'})`
    },
    data: (row, column) => {
      const list =  [
        {
          label: '签到',
          value: 'sign',
          atClick: (row) => onSignPatientByCardNo(row),
          condition: (row) => [QueueStateEnum.AWAIT_SIGN, QueueStateEnum.ALREADY_CALLED, QueueStateEnum.ALREADY_PASSED, QueueStateEnum.ALREADY_COMPLETED].includes(row.state),
        },
        {
          label: '指派医生',
          value: 'setDoctor',
          atClick: (row) => onSetPatientEmployee(row),
          condition: (row) => [QueueStateEnum.AWAIT_SIGN, QueueStateEnum.AWAIT_CALL, QueueStateEnum.ALREADY_CALLED, QueueStateEnum.ALREADY_PASSED, QueueStateEnum.AWAIT_REVIEW, QueueStateEnum.ALREADY_COMPLETED].includes(row.state),
        },
        {
          label: '取消指派',
          value: 'clearDoctor',
          atClick: (row) => onClearPatientEmployee(row),
          condition: (row) => JSON.stringify(row.doctorName) != null,
        },
        {
          label: '设置优先级',
          value: 'setPriority',
          atClick: (row) => {onSetPatientPriority(row)},
          condition: (row) => [QueueStateEnum.AWAIT_SIGN, QueueStateEnum.AWAIT_CALL, QueueStateEnum.AWAIT_REVIEW].includes(row.state),
        },
        {
          label: '重呼',
          value: 'again',
          atClick: (row) => onAgainCallByRegId(row),
          condition: (row) => [QueueStateEnum.ALREADY_CALLED, QueueStateEnum.ALREADY_PASSED, QueueStateEnum.AWAIT_REVIEW, QueueStateEnum.ALREADY_COMPLETED].includes(row.state),
        },
        // {
        //   label: '复诊',
        //   value: 'follow',
        //   atClick: (row) => {},
        // },
        {
          label: '过号',
          value: 'passed',
          atClick: (row) => onPassedAlreadyCalled(row),
          condition: (row) => [QueueStateEnum.AWAIT_CALL, QueueStateEnum.ALREADY_CALLED].includes(row.state),
        },
        {
          label: '就诊完成',
          value: 'complete',
          atClick: (row) => onCompletePatientByRegId(row),
          condition: (row) => [QueueStateEnum.AWAIT_SIGN, QueueStateEnum.AWAIT_CALL, QueueStateEnum.ALREADY_CALLED, QueueStateEnum.ALREADY_PASSED, QueueStateEnum.AWAIT_REVIEW].includes(row.state),
        },
        {
          label: '取号',
          value: 'number',
          atClick: (row) => onNumberPatientByCardNo(row),
          condition: (row) => [QueueStateEnum.AWAIT_CALL, ].includes(row.state),
        },
      ]
      return list
    }
  }
})
const patientCardNumInputRef = ref()
const patientCard = reactive({
  state: -1,
  source: '-1',
  type: 'card',
  value: ''
})
const selectDeptId = ref()
const selectedItem = ref()
const selectedDoctor = ref()
const patientSignSuccessDialogRef = ref()
const setPatientToEmployeeDialogRef = ref()
const setPatientToPriorityDialogRef = ref()
const patientSearchDialogRef = ref()
const searchDoctorKey = ref()

const doctorCurrentList = ref<QueueScheduleModel[]>([])

let _timeout = null

onBeforeMount(() => {
  listTodaySchedule()
  document.body.addEventListener('click', onSetCardNumInputFocus)
  patientCard.type = StorageUtils.getLocalStorage("NURSE_SELECT_CARD_TYPE") || 'card'
})

onBeforeUnmount(() => {
  document.body.removeEventListener('click', onSetCardNumInputFocus)
})


const onSelectPatientCardType = () => {
  StorageUtils.setLocalStorage("NURSE_SELECT_CARD_TYPE", patientCard.type)
  onSetCardNumInputFocus()
}

const onSetCardNumInputFocus = () => {
  patientCardNumInputRef.value?.focus()
}

const onSetReadCardNo = (cardNo) => {
   patientCard.value = cardNo
}

const onChangeDepart = ({deptId, depart}) => {
  selectDeptId.value = deptId && depart ? deptId : null
  listTodaySchedule()
  onSetCardNumInputFocus()
}
const listTodaySchedule = () => {
  itemTable.isLoading = true
  // 根据设备code查询关联的科目
  NurseClientApi.getItemListByIds(selectDeptId.value).then((data) => {
    itemTable.data = data
    if (data?.length) {
      selectedItem.value = data[0]
    } else {
      selectedDoctor.value = null
      doctorTable.data = []
      patientTable.data = []
    }
    itemTable.isLoading = false
  }, () => itemTable.isLoading = false)
}

const onSelectItem = (item: QueueRegItemModel) => {
  selectedItem.value = item
  if (_timeout) {
    clearTimeout(_timeout)
    _timeout = null
  }
  if (selectedItem.value) {
    listTodayItemEmployee()
    listTodayEmployeePatient()
  }
}

const onSelectDoctor = (doctor: EmployeeModel) => {
  // selectedDoctor.value = doctor
  // if (selectedDoctor.value) {
  //   // listTodayEmployeePatient()
  // }
}

const listTodayItemEmployee = () => {
  doctorTable.isLoading = true
  NurseClientApi.getTodayEmplyeeByItem(selectedItem.value.departId, selectedItem.value.itemId).then((data) => {
    doctorCurrentList.value = data
    doctorTable.data = searchDoctorKey.value ? data.filter(item => item.doctorCode.includes(searchDoctorKey.value) || item.doctorName.includes(searchDoctorKey.value)) : data
    if (doctorTable.data?.length) {
      selectedDoctor.value = doctorTable.data[0]
    }
    doctorTable.isLoading = false
  }, () => doctorTable.isLoading = false)
}

const onClearPatientCard = () => {
  patientCard.value = ''
  if (_timeout) {
    clearTimeout(_timeout)
    _timeout = null
  }
  listTodayEmployeePatient()
}

const listTodayEmployeePatient = (pageIndex = 1) => {
  if(!selectedItem.value) return
  patientTable.isLoading = true
  if(_timeout) {
    clearTimeout(_timeout)
    _timeout = null
  }
  let searchKey = ''
  if (patientCard.type === 'name') {
    searchKey = patientCard.value
  }
  NurseClientApi.getEmployeePatientList(selectedItem.value.departId, selectedItem.value.itemId,patientCard.state == -1 ? null : patientCard.state, patientCard.source == '-1' ? null : patientCard.source, searchKey, pageIndex, patientTable.paging.pageSize).then(pagingData => {
    patientTable.data = pagingData.data
    patientTable.paging = Object.assign({}, patientTable.paging, {
      total: pagingData.total,
      pageIndex: pagingData.pageIndex
    })
    patientTable.isLoading = false
    if (patientTable.paging.pageIndex === 1) {
      _timeout = setTimeout(() => {
        listTodayEmployeePatient(patientTable.paging.pageIndex)
      }, 30 * 1000)
    }
  }, () => {
    patientTable.isLoading = false
    if (patientTable.paging.pageIndex === 1) {
      _timeout = setTimeout(() => {
        listTodayEmployeePatient(patientTable.paging.pageIndex)
      }, 30 * 1000)
    }
  })

  onSetCardNumInputFocus()
}

const onSearchPatient = () => {
  if (patientCard.type === 'card') {
    onShowPatientSearch()
  } else {
    listTodayEmployeePatient(1)
  }
}

const onSetDoctorSuccess = (patient: QueueItemModel) => {
  patientSignSuccessDialogRef.value.onShowDialog(patient)
  if (_timeout) {
    clearTimeout(_timeout)
    _timeout = null
  }
  listTodayEmployeePatient()
}

const onSignPatientByCardNo = (patient: QueueItemModel) => {
  NurseClientApi.signPatientByRegId(patient.registerId).then((res) => {
    patientSignSuccessDialogRef.value.onShowDialog(res)
    if (_timeout) {
      clearTimeout(_timeout)
      _timeout = null
    }
    listTodayEmployeePatient(patientTable.paging.pageIndex)
  })
}

// 取号按钮
const onNumberPatientByCardNo = (patient: QueueItemModel) => {
  NurseClientApi.numberPatientByRegId(patient.registerId).then((res) => {
    ElMessage.success("操作成功，正在打印中...");
  }, () => {})
}

// 过号按钮
const onPassedAlreadyCalled = (patient: QueueItemModel) => {
  NurseClientApi.passedPatientByRegId(patient.registerId).then((res) => {
    ElMessage.success("操作成功");
    listTodayEmployeePatient(patientTable.paging.pageIndex)
  }, () => {})
}

// 就诊完成
const onCompletePatientByRegId = (patient: QueueItemModel) => {
  NurseClientApi.completePatientByRegId(patient.registerId).then((res) => {
    ElMessage.success("操作成功");
    listTodayEmployeePatient(patientTable.paging.pageIndex)
  }, () => {})
}

// 重呼
const onAgainCallByRegId = (patient: QueueItemModel) => {
  NurseClientApi.AgainCallByRegId(patient.registerId).then((res) => {
    ElMessage.success("操作成功");
    listTodayEmployeePatient(patientTable.paging.pageIndex)
  }, () => {})
}

const onSetPatientEmployee = (patient: QueueItemModel) => {
  setPatientToEmployeeDialogRef.value.onShowDialog(patient)
}

const onSetPatientPriority = (patient: QueueItemModel) => {
  setPatientToPriorityDialogRef.value.onShowDialog(patient)
}

// 取消指派
const onClearPatientEmployee = (patient: QueueItemModel) => {
  NurseClientApi.clearPatientEmployeeByRegId(patient.registerId, patient.itemId, patient.departId, patient.categoryId, patient.subQueueFlag).then((res) => {
    ElMessage.success("操作成功");
    listTodayEmployeePatient(patientTable.paging.pageIndex)
  }, () => {})
}

const onShowPatientSearch = () => {
  patientSearchDialogRef.value.onShowDialog(selectedItem.value.departId, selectedItem.value.itemId, patientCard.value)
}
const onFilterDoctor = () => {
  doctorTable.data = searchDoctorKey.value ? doctorCurrentList.value.filter(item => item.doctorCode.includes(searchDoctorKey.value) || item.doctorName.includes(searchDoctorKey.value)) : doctorCurrentList.value
}

</script>

<style scoped lang="scss">
.yy-nurse-sign {
  display: flex;
  height: 100%;
  width: 100%;
  user-select: none;
  &_header {
    display: flex;
    flex-direction: row;
    padding: 10px 5px;
    align-items: center;
    border-bottom: 1px solid #f1f1f1;
    line-height: 32px;
    &-title {
      font-size: 16px;
      font-weight: bold;
    }
    &-search {
      margin-left: auto;
      width: 50%;
      :deep(.el-select__wrapper) {
        border-radius: 16px;
      }
      :deep(.el-input__wrapper) {
        border-radius: 16px;
      }
    }
  }
  &_doctor {
    flex: 0 0 300px;
    display: flex;
    flex-direction: column;
    background: #fff;
    border-right: 5px solid #d1d1d1;
    min-width: 0;
    &-item {
      flex: 2;
      display: flex;
      flex-direction: column;
      min-height: 0;
    }
    &-list {
      border-top: 5px solid #d1d1d1;
      flex: 1;
      display: flex;
      flex-direction: column;
      min-height: 0;
    }
  }
  &_patient{
    background: #fff;
    flex: auto;
    display: flex;
    flex-direction: column;
    min-width: 0;
    &-header {

    }
  }
  &_body {
    flex: 1;
    min-height: 0;
  }
}
</style>
